package org.garbagecan.quartzstudy.cron;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.calendar.WeeklyCalendar;

public class TestRangeCalendar {
	public static void test() throws Exception {
		print("\nTestRangeCalendar.test: -------------------------------");

		// long start = parseToDate("2006-01-01 00:00:00.000").getTime();
		// long end = parseToDate("2007-01-01 00:00:00.000").getTime();
		// long start = parseToDate("2007-01-01 00:00:00.000").getTime();
		// long end = parseToDate("2008-01-01 00:00:00.000").getTime();
		long start = parseToDate("2007-02-15 15:13:00.000").getTime();
		long end = parseToDate("2007-02-15 15:14:00.000").getTime();

		long timeStamp = parseToDate("2007-02-17 00:00:00.000").getTime();// Wed
		RangeCalendar rc = new RangeCalendar(start, end);

		// By default it excludes SATURDAY and SUNDAY.
		WeeklyCalendar wc = new WeeklyCalendar();
		// print(wc.isDayExcluded(0));
		// print(wc.isDayExcluded(6));
		// print(wc.isDayExcluded(7)); // error

		print(wc.isTimeIncluded(timeStamp));
		print(rc.isTimeIncluded(timeStamp));

		// timeStamp = wc.getNextIncludedTime(timeStamp);
		// print(new Date(timeStamp));
		// timeStamp = wc.getNextIncludedTime(timeStamp);
		// print(new Date(timeStamp));

		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler scheduler = sf.getScheduler();
		
		JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("myjob","mygroup").build();
		
		Trigger trigger = TriggerBuilder.newTrigger()
				.withIdentity("mytrigger", "mygroup")
				.forJob(jobDetail)
				.startNow()
				.withPriority(5)
				.modifiedByCalendar("cal")
				.withSchedule(CronScheduleBuilder
					.cronSchedule("* * * * * ? 2007"))
				.build();

		scheduler.addCalendar("cal", rc, true, true);

		scheduler.scheduleJob(jobDetail, trigger);

		scheduler.start();
	}

	public static Date parseToDate(String s) throws ParseException {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = df.parse(s);
		return date;
	}

	public static void print(Object obj) {
		System.out.print("\t");
		System.out.println(obj);
	}
}
